package com.example.demo.file.impl;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import com.example.demo.entity.FileUpReturnEntity;
import com.example.demo.file.FileManager;
import com.example.demo.file.FileManagerFactory;
import com.example.demo.util.CommonUtil;
import com.example.demo.util.FileUtils;
import com.example.demo.util.PrimaryKeyUtil;
import com.example.demo.util.PropertiesUtil;
import com.example.demo.util.SftpUtil;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SftpFileManager implements FileManager{
	private final String SAVETYPE = "1";
	
	@Override
	public FileUpReturnEntity uploadSingleFile(MultipartFile file, String module, boolean dontChangeName,
			boolean dontCreateDateDir) throws Exception {
		
		String fileDir = PropertiesUtil.getProperty("sftp.filepath");
		String fileUrlPrefix = PropertiesUtil.getProperty("sftp.prefix");
		
		fileDir = fileDir.endsWith("/")?fileDir:(fileDir+"/");
		fileUrlPrefix = fileUrlPrefix.endsWith("/")?fileUrlPrefix:(fileUrlPrefix+"/");

		fileDir += module + "/";
		fileUrlPrefix += module + "/";
		
		
		String fileName = PrimaryKeyUtil.getUUIDWithOutLink() + FileUtils.getFileFormat(file.getOriginalFilename());
		if(!dontCreateDateDir) {
			String dateDir = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
			fileDir += dateDir + "/";
			fileUrlPrefix += dateDir + "/";
		}
		
		if(dontChangeName) {
			fileName = file.getOriginalFilename();
		}
		
		String fileUrl = fileUrlPrefix+fileName;
		
		log.info("文件保存路径>>>{},文件url>>>{}",(fileDir+fileName),fileUrl);
		
		SftpUtil sftpUtil = new SftpUtil(true);
		
		sftpUtil.uploadFile(fileDir, fileName, file.getInputStream());
		
		log.info("上传文件到sftp服务器完成");
		
		return new FileUpReturnEntity(fileUrl, SAVETYPE);
	}

	@Override
	public List<FileUpReturnEntity> uploadMultiFile(MultipartFile[] files, String module, boolean dontChangeName,
			boolean dontCreateDateDir) throws Exception {

		String fileDir = PropertiesUtil.getProperty("sftp.filepath");
		String fileUrlPrefix = PropertiesUtil.getProperty("sftp.prefix");
		
		fileDir = fileDir.endsWith("/")?fileDir:(fileDir+"/");
		fileUrlPrefix = fileUrlPrefix.endsWith("/")?fileUrlPrefix:(fileUrlPrefix+"/");

		fileDir += module + "/";
		fileUrlPrefix += module + "/";
		
		if(!dontCreateDateDir) {
			String dateDir = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
			fileDir += dateDir + "/";
			fileUrlPrefix += dateDir + "/";
		}
		
		List<FileUpReturnEntity> sftpFileList = new ArrayList<>();
		
		SftpUtil sftpUtil = new SftpUtil(true);
		
		int fileNum = files.length;
		
		for (int i = 0; i < fileNum; i++) {
			MultipartFile file = files[i];
			
			String fileName = PrimaryKeyUtil.getUUIDWithOutLink() + FileUtils.getFileFormat(file.getOriginalFilename());
			
			if(dontChangeName) {
				fileName = file.getOriginalFilename();
			}
			
			String fileUrl = fileUrlPrefix+fileName;
			
			log.info("文件保存路径>>>{},文件url>>>{}",(fileDir+fileName),fileUrl);
			
			sftpUtil.uploadFile(fileDir, fileName, file.getInputStream());
			
			sftpFileList.add(new FileUpReturnEntity(fileUrl, SAVETYPE));
		}
		
		log.info("多文件上传至sftp服务器完成");
		
		return sftpFileList;
	}
	public static void main(String[] args) throws FileNotFoundException, IOException {
		PropertiesUtil.initProperty();
		FileManager fm = FileManagerFactory.build("2");
		
		MultipartFile file = new MockMultipartFile("addFile.jpg", "addFile.jpg", null, new FileInputStream("E:\\图片\\icon图片\\addFile.jpg"));
		MultipartFile file2 = new MockMultipartFile("线上答题2.png", "线上答题2.png", null, new FileInputStream("E:\\图片\\icon图片\\线上答题2.png"));
		
		MultipartFile[] files = new MultipartFile[2];
		files[0] = file;
		files[1] = file2;
				
		
		try {
//			fm.uploadSingleFile(file2, "PC-sftp-test", false, false);
			fm.uploadMultiFile(files, "pc-oss-test", false, false);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void readFileFromRequest(HttpServletResponse response, String fileUrl) throws Exception {
		// TODO Auto-generated method stub
		log.info("(sftp)文件访问路径为>>>{}",fileUrl);
		
		fileUrl = CommonUtil.encodeUrlCN(fileUrl);
		
		String fileName = fileUrl.substring(fileUrl.indexOf("/")+1);
		
		URL url = new URL(fileUrl);
		
		HttpURLConnection connect = (HttpURLConnection)url.openConnection();
		
		connect.setConnectTimeout(5000);
		
		response.setContentType(CommonUtil.getContentType(fileName));
		response.setHeader("Content-disposition", "inline; filename=" + fileName);
		
		InputStream fileStream = connect.getInputStream();
		ServletOutputStream sos = response.getOutputStream();
		
		//读取文件流并返回给response
		IOUtils.copy(fileStream, sos);
		
        log.info("(sftp){}文件访问成功,已输出至响应中去",fileUrl);
        
        IOUtils.closeQuietly(sos);
        IOUtils.closeQuietly(fileStream);
        
        if(null!=connect) {
        	connect.disconnect();
        }
        
        log.info("(sftp)关闭连接");
	}

}
